package com.zijie.shopgateway.config;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

//@Component
public class AuthFilter implements GlobalFilter {
    private GatewayConfig gatewayConfig;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest req = exchange.getRequest();
        String uri = req.getPath().toString();//当前请求路径
        String ctx = req.getPath().contextPath().value();//上下文路径
        uri = uri.replace(ctx, "");//无上下文的请求路径
        String method = req.getMethod().toString();
        System.out.println(uri);
        final String finalUri = uri;

        //对白名单中的地址直接放行
        List<String> ignoreUrls = gatewayConfig.getWhiteList();
        PathMatcher matcher = new AntPathMatcher();
        for (String pattern : ignoreUrls) {
            UriPattern up = UriPattern.of(pattern);
            if (matcher.match(up.pattern(), uri) && up.matchMethod(method)) {
                return chain.filter(exchange);//直接放行
            }
        }
        return null;
    }
    private record UriPattern(String[] allowedMethods, String pattern) {
        //判断是否匹配某个请求类型
        private boolean matchMethod(String method) {
            for (String am : allowedMethods) {
                if (am.equalsIgnoreCase(method) || am.equals("*")) {
                    return true;
                }
            }
            return false;
        }

        private static UriPattern of(String uri) {
            String[] parts = uri.split(":");
            if (parts.length == 1) {
                return new UriPattern(new String[]{"*"}, parts[0]);
            } else {
                return new UriPattern(parts[0].split(","), parts[1]);
            }
        }
    }
}
